#include "TrMasters.h"
#include "TrCurlUtils.h"
#include "nlohmann/json.hpp"
#include "TrUtils.h"
#include <unordered_map>

using nJson = nlohmann::json;

static std::map<std::string, std::string>			gs_codeMasters;
static std::map<std::string, std::string>			gs_codeNextMasters;


TrMasters::TrMasters()
{
	TrCurlUtils* pCurl = new TrCurlUtils;
	std::string resData;
	pCurl->Gets("https://xledoo.com/api/futures/master", resData);

	nJson jRoot = nJson::parse(resData.c_str());
	if (jRoot["code"] == 1)
	{
		nJson d = nJson::parse(jRoot["data"].get<std::string>().c_str());
		if (d.is_array())
		{
			for (const auto& e : d) {
				std::string code = e["n"].get<std::string>();
				std::string product = e["p"].get<std::string>();
				Contract c = Trget(code);
				if (c.m_strName.size() < 3)
					continue;

				if (!TrUtils::if_maphas(gs_codeMasters, code))
				{
					gs_codeMasters.insert({ product , code });
				}
			}
		}
	}
}

std::map<std::string, std::string> TrMasters::master()
{
	return gs_codeMasters;
}

std::map<std::string, std::string> TrMasters::master_next()
{
	return gs_codeNextMasters;
}

std::string TrMasters::master(const std::string& proId)
{
	auto it = gs_codeMasters.find(proId);
	if (it != gs_codeMasters.end())
	{
		return it->second;
	}
	return std::string();
}

std::string TrMasters::master_next(const std::string& proId)
{
	auto it = gs_codeNextMasters.find(proId);
	if (it != gs_codeNextMasters.end())
	{
		return it->second;
	}
	return std::string();
}
